package com.aaa.member.service.impl;

import com.aaa.common.bo.CouponHistory;
import com.aaa.common.bo.TbCar;
import com.aaa.common.constant.ExceptionConstant;
import com.aaa.common.constant.ReturnCode;
import com.aaa.common.util.CustomException;
import com.aaa.common.util.Result;
import com.aaa.member.dao.AccountStatementDao;
import com.aaa.member.dao.TbOrderDao;
import com.aaa.member.entity.*;
import com.aaa.member.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (TbOrder)表服务实现类
 *
 * @author makejava
 * @since 2020-11-18 09:06:05
 */
@Service("tbOrderService")
public class TbOrderServiceImpl implements TbOrderService {
    @Resource
    private TbOrderDao tbOrderDao;

    //注入账户流水表
    @Autowired
    private AccountStatementService accountStatementService;

    //注入积分历史表
    @Autowired
    private IntegrationHistoryService integrationHistoryService;

    //注入远程操作会员优惠券
    @Autowired
    private CouponService couponService;

    //注入远程操作车辆状态
    @Autowired
    private CarService carService;

    //注入会员
    @Autowired
    private TbMemberService tbMemberService;

    //注入会员等级
    @Autowired
    private MemberLevelService memberLevelService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public TbOrder queryById(Integer id) {
        return this.tbOrderDao.queryById(id);
    }

    @Override
    public Result queryAllOrder(Integer pageNo,Integer pageSize,String memberName, Integer orderstate, String brandtypename,String vin) {
        //分页
        PageHelper.startPage(pageNo,pageSize);
        PageInfo<Map> pageInfo = new PageInfo<Map>(tbOrderDao.queryAllOrder(memberName,orderstate,brandtypename,vin));
        return new Result(ReturnCode.SUCCESSS.getCode(),
                ReturnCode.SUCCESSS.getMsg(),pageInfo);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<TbOrder> queryAllByLimit(int offset, int limit) {
        return this.tbOrderDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param tbOrder 实例对象
     * @return 实例对象
     */
    @Override
    public TbOrder insert(TbOrder tbOrder) {
        //计算消费金额，更新订单总金额
        // 获取该用户的优惠券，添加客户优惠券关联表
        //向账号流水表添加数据
        //计算积分，添加客户积分历史，更新成长值，账户余额，更新用户积分和历史积分
        //更新车辆状态
        System.out.println("车辆ID："+tbOrder.getCarId());
        TbCar rentCar = carService.selectOne(tbOrder.getCarId());
        //获取租车价钱
        Object price=rentCar.getPrice();
        System.out.println("该车租价："+price);
        //计算租车时间
        Date startTime=tbOrder.getStartTime();
        Date endTime=tbOrder.getEndTime();
        //获取1970午夜到现在的毫秒
        long stime =startTime.getTime();
        long etime =endTime.getTime();
        //时间相减
        double days=(etime-stime)/1000/3600/24;
        //天数有小数点，四舍五入
        int tdays=(int) days;
        int totalDay=tdays+((tdays-days)>0.5?1:0);
        System.out.println("租车天数："+totalDay);
        double rentalPrice = Double.valueOf(price.toString())*totalDay;
        System.out.println("预付价格："+rentalPrice);
        //可以再加上其他费用

        tbOrder.setPreparidAmount(rentalPrice);
        //添加订单
        this.tbOrderDao.insert(tbOrder);
        System.out.println("添加返回Order"+tbOrder);
        //获取当前时间
        Date currentTime=new Date();
        //计算消费金额，更新订单总金额
        double PreparidAmount = tbOrder.getPreparidAmount();
        Map map = new HashMap();
        //获取客户id
        map.put("memberId",tbOrder.getClientId());
        //获取门店id
        map.put("shopId",tbOrder.getBrrowShop());
        //获取该用户优惠券，添加客户优惠券关联表
        System.out.println(map);
        Result result=couponService.queryUseCoupon(map);
        Object data =result.getData();
        double tempAmount=0;
        if (data!=null) {
            List<Map> couponList = (List<Map>) data;
            CouponHistory couponHistory = null;
            for (Map couponMap : couponList
            ) {
                //使用优惠券可能多张
                tempAmount += Double.valueOf(couponMap.get("amount") + "");
                couponHistory = new CouponHistory();
                //这里获取优惠券历史id，和优惠券id同名，可能出错
                couponHistory.setId(Long.valueOf(couponMap.get("id") + ""));
                couponHistory.setOrderId(Long.valueOf(tbOrder.getId()));
                //1为优惠券已使用
                couponHistory.setUseStatus(1);
                couponHistory.setUseTime(currentTime);
                //修改优惠券状态
                couponService.update(couponHistory);
            }
        }
            //减去优惠券金额
                double endAmount = PreparidAmount - tempAmount;
                System.out.println(endAmount);
                //更新订单金额
                tbOrder.setTotalPrice(endAmount);
                //1为订单正在进行
                tbOrder.setState(1);
                tbOrderDao.update(tbOrder);

                System.out.println("算完金额后的总金额"+endAmount);
                //向账号流水表添加数据
                AccountStatement accountStatement=new AccountStatement();
                accountStatement.setClientId(tbOrder.getClientId());
                accountStatement.setAmount(endAmount);
                accountStatement.setAddtime(currentTime);
                //accountStatement.setTypeId(ServiceCostant.AccountStatementType.PAY);
                //accountStatement.setPayId(tbOrder.getPayType());
                accountStatementService.insert(accountStatement);

                System.out.println("计算积分"+tbOrder);
                //计算积分，添加客户积分历史，更新成长值，账户余额，更新用户积分和历史积分
                TbMember tbMember = tbMemberService.queryById(tbOrder.getClientId());
                System.out.println("账户余额"+tbMember.getAccountBalance());
                if (tbMember.getAccountBalance()>0){
                    tbMember.setAccountBalance(tbMember.getAccountBalance()-endAmount);
                }
                int currentGrowth=(int)(tbMember.getGrowth()+endAmount);
                tbMember.setGrowth((int) (currentGrowth));
                //根据用户id查询用户级别、

                MemberLevel memberLevel = memberLevelService.queryById(tbMember.getMemberLevelId());
                double currentIntegration=0;
                if(memberLevel!=null){
                    Double ratio=memberLevel.getRatio();
                    currentIntegration=endAmount*ratio;
                }
                //更新积分
                tbMember.setIntegration((int) (tbMember.getIntegration()+currentIntegration));
                tbMember.setHistoryIntegration((int) (tbMember.getHistoryIntegration()+currentIntegration));
                //获取会员等级
                System.out.println("等级"+memberLevel);
                List<MemberLevel> memberLevels=memberLevelService.queryAll(null);

                //判断会员下订单后加完成长值的等级变化
                if (memberLevels!=null&&memberLevels.size()>0){
                    for (MemberLevel level :memberLevels
                            ) {
                        if (currentGrowth<level.getGrowthPoint()){
                            //更新会员最新等级
                            tbMember.setMemberLevelId(Integer.valueOf(level.getId()+""));
                            break;
                        }
                    }
                }
                tbMemberService.updatePassword(tbMember);

                //添加客户历史积分表
                IntegrationHistory integrationHistory=new IntegrationHistory();
                integrationHistory.setMemberId(Long.valueOf(tbOrder.getClientId()));
                integrationHistory.setCreateTime(currentTime);
                //integrationHistory.setChangeType();
                integrationHistory.setChangeCount((int) currentIntegration);
                integrationHistory.setOperateMan(tbMember.getUsername());
                System.out.println("操作人"+tbMember.getUsername());
                integrationHistory.setOperateNote("消费积分");
                integrationHistoryService.insert(integrationHistory);

                //更新车辆状态
                TbCar tbCar = new TbCar();
                tbCar.setId(tbOrder.getCarId());
                //2为车辆已租出
                tbCar.setState(2);
                Result updateCar = carService.update(tbCar);
        return tbOrder;
    }

    /**
     * 修改状态为未完成的订单信息
     *
     * @param tbOrder 实例对象
     * @return 实例对象
     */
    @Override
    public TbOrder update(TbOrder tbOrder) {
        this.tbOrderDao.update(tbOrder);
        return this.queryById(tbOrder.getId());
    }

    /**
     * 删除订单为未完成的订单信息
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.tbOrderDao.deleteById(id) > 0;
    }
}